const webpack = require("webpack");
const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const FileManagerPlugin = require("filemanager-webpack-plugin");
const ReactRefreshWebpackPlugin = require("@pmmmwh/react-refresh-webpack-plugin");
const WebpackBar = require("webpackbar");

module.exports = ({ isDev, isPro, inputRootDir, outputRootDir, pkRootDir, pkName, pkVersion }) => {
  /** @type {import('webpack').Configuration} */
  return {
    plugins: [
      new WebpackBar(),
      new webpack.DefinePlugin({
        "window.ENV": JSON.stringify(isPro ? "production" : "development"), // 定义全局变量
      }),
      new HtmlWebpackPlugin({
        // 定义html文件
        template: path.resolve(__dirname, inputRootDir, "asset/index.html"),
        favicon: path.resolve(__dirname, inputRootDir, "asset/favicon.ico"),
        title: "牛年创建的react单页非服务端渲染模板",
      }),
      isPro &&
        new MiniCssExtractPlugin({
          // 生成环境 压缩css以及输出文件配置 默认生成环境压缩
          filename: "[name].[contenthash:6].css",
        }),
      isPro &&
        new FileManagerPlugin({
          // 生成环境 打包完成后根据包生成备份zip
          events: {
            onEnd: {
              archive: [
                {
                  source: path.resolve(__dirname, outputRootDir),
                  destination: path.resolve(__dirname, pkRootDir, `${pkName}-${pkVersion}.zip`),
                },
              ],
            },
          },
        }),
      // react提供的热更新
      isDev &&
        new ReactRefreshWebpackPlugin({
          // react提供的热更新
          overlay: false,
          exclude: [/node_modules/, /dist/],
        }),
    ].filter(Boolean),
  };
};
